package com.geostar.constructionland.attachment.controller.planningReview;

import com.geostar.constructionland.attachment.mapper.planningReview.PlanningReviewMapper;
import com.geostar.constructionland.attachment.service.planningReview.PlanningReviewService;
import com.geostar.constructionland.attachment.util.FTPUtil;
import com.geostar.constructionland.attachment.util.UnZipUtils;
import com.geostar.constructionland.common.entity.response.ServerResponse;
import com.geostar.constructionland.common.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 规划审核
 */
@Slf4j
@RestController
@RequestMapping(path = "/planningReview")
@Api(tags = "规划审核相关接口")
public class PlanningReviewController {

    @Autowired
    private FTPUtil ftpUtil;
    @Resource
    private PlanningReviewService planningReviewService;
    @Resource
    PlanningReviewMapper planningReviewMapper;

    @Value("${automatic.planningReviewFTPAddress}")
    String planningReviewFTPAddress;
    @Value("${automatic.planningReviewFTPPort}")
    int planningReviewFTPPort;
    @Value("${automatic.planningReviewFTPUsername}")
    String planningReviewFTPUsername;
    @Value("${automatic.planningReviewFTPPassword}")
    String planningReviewFTPPassword;
    @Value("${automatic.planningReviewFTPZipPassword}")
    String planningReviewFTPZipPassword;
    /** 提取附件目录名称（进件） */
    @Value("${automatic.planningReviewExtractAttachmentDirName}")
    String planningReviewExtractAttachmentDirName;
    /** 补正附件目录名称（补正材料） */
    @Value("${automatic.planningReviewCorrectionAttachmentDirName}")
    String planningReviewCorrectionAttachmentDirName;

    @Value("${automatic.tmpFilePath}")
    String tmpFilePath;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "ywid", value = "业务ID", required = true),
            @ApiImplicitParam(name = "ftpPath", value = "FTP路径", required = true),
            @ApiImplicitParam(name = "ftpFileName", value = "FTP文件名称", required = true),
            @ApiImplicitParam(name = "version", value = "附件版本号", required = true)
    })
    @ApiModelProperty(value = "查询当前附件提取进度状态")
    @RequestMapping(value = "/queryExtractAttachmentState")
    @ResponseBody
    public ServerResponse queryExtractAttachmentState(@RequestParam("ywid") String ywid, @RequestParam("ftpPath") String ftpPath,
                                                      @RequestParam("ftpFileName") String ftpFileName, @RequestParam("version") Integer version) {
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("state", "new");
        ServerResponse serverResponse = ServerResponse.createBySuccess("附件未提取", dataMap);
        // 查询是否该附件是否已经提取
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("ywid", ywid);
        param.put("attachmentName", ftpFileName);
        List<Map<String, Object>> result = null;
        if(version == 1) {
            param.put("attachmentDirName", planningReviewExtractAttachmentDirName);
            result = (List<Map<String, Object>>) planningReviewMapper.queryAttachmentDirectoryInstByDirName(param);
        } else {
            param.put("version", version);
            result = (List<Map<String, Object>>) planningReviewMapper.queryAttachmentDirectoryInstByVersion(param);
        }
        if(! CollectionUtils.isEmpty(result)) {
            String fjmlid = (String) result.get(0).get("FJMLID");
            if(StringUtils.isNotBlank(fjmlid)) {
                dataMap.put("state", "finished");
                return ServerResponse.createBySuccess("附件已提取", dataMap);
            }
        }
        String zipFileName = ftpFileName;
        if(! ftpFileName.contains(".zip")) {
            zipFileName += ".zip";
        }
        String tmpZipFileDir = tmpFilePath + File.separator + zipFileName;
        File file = new File(tmpZipFileDir);
        if (file.exists()) {
            Long fileSize = ftpUtil.getSize(planningReviewFTPAddress, planningReviewFTPPort, planningReviewFTPUsername, planningReviewFTPPassword, ftpPath, zipFileName);
            if(fileSize != null && fileSize == file.length()) {
                dataMap.put("state", "existentCompressedPackage");
                return ServerResponse.createBySuccess("附件已下载", dataMap);
            }
        }
        return serverResponse;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "ftpPath", value = "FTP路径", required = true),
            @ApiImplicitParam(name = "ftpFileName", value = "FTP文件名称", required = true)
    })
    @ApiModelProperty(value = "下载所提取附件")
    @RequestMapping(value = "/downloadAttachment")
    @ResponseBody
    public ServerResponse downloadAttachment(@RequestParam("ftpPath") String ftpPath, @RequestParam("ftpFileName") String ftpFileName) {
        ServerResponse serverResponse = ServerResponse.createBySuccessMessage("操作成功！");
        if(! ftpFileName.contains(".zip")) {
            ftpFileName += ".zip";
        }
        /** 下载压缩包 */
        long startTime = System.currentTimeMillis();    //获取开始时间
        log.info("##########下载压缩包，开始");
        boolean downloadFileResult = ftpUtil.downloadFile(planningReviewFTPAddress, planningReviewFTPPort, planningReviewFTPUsername, planningReviewFTPPassword, ftpPath, ftpFileName, tmpFilePath);
        if(! downloadFileResult) {
            return ServerResponse.createByErrorCodeMessage(1001,"附件下载失败！");
        }
        long endTime = System.currentTimeMillis();    //获取结束时间
        log.info("##########下载压缩包，用时：{}ms", endTime - startTime);
        return serverResponse;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "ftpFileName", value = "FTP文件名称", required = true)
    })
    @ApiModelProperty(value = "解压所提取附件")
    @RequestMapping(value = "/unzipAttachment")
    @ResponseBody
    public ServerResponse unzipAttachment(@RequestParam("ftpFileName") String ftpFileName) {
        ServerResponse serverResponse = ServerResponse.createBySuccessMessage("操作成功！");
        String zipFileName = ftpFileName;
        if(ftpFileName.contains(".zip")) {
            zipFileName = ftpFileName.replace(".zip", "");
        } else {
            ftpFileName += ".zip";
        }
        String tmpZipFilePath = tmpFilePath + File.separator + ftpFileName;
        String tmpZipFileDir = tmpFilePath + File.separator + zipFileName;
        log.info("##########ZIP文件解压缩，开始");
        long startTime = System.currentTimeMillis();    //获取开始时间
        try {
            UnZipUtils.unZip(tmpZipFilePath, tmpZipFileDir, planningReviewFTPZipPassword);
        } catch (ZipException e) {
            log.error("##########附件解压失败：", e);
            return ServerResponse.createByErrorCodeMessage(1002,"附件解压失败！");
        }
        long endTime = System.currentTimeMillis();    //获取结束时间
        log.info("##########ZIP文件解压缩，用时：{}ms", endTime - startTime);
        return serverResponse;
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "ywid", value = "业务ID", required = true),
            @ApiImplicitParam(name = "ywxl", value = "业务小类", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "userName", value = "用户名称", required = true),
            @ApiImplicitParam(name = "ftpPath", value = "FTP路径", required = true),
            @ApiImplicitParam(name = "ftpFileName", value = "FTP文件名称", required = true),
            @ApiImplicitParam(name = "version", value = "附件版本号", required = true)
    })
    @ApiModelProperty(value = "上传所提取附件")
    @RequestMapping(value = "/uploadAttachment")
    @ResponseBody
    public ServerResponse uploadAttachment(@RequestParam("ywid") String ywid, @RequestParam("ywxl") String ywxl,
                                            @RequestParam("userId") String userId, @RequestParam("userName") String userName,
                                            @RequestParam("ftpFileName") String ftpFileName, @RequestParam("version") Integer version) {
        ServerResponse serverResponse = ServerResponse.createBySuccessMessage("操作成功！");
        String zipFileName = ftpFileName;
        if(ftpFileName.contains(".zip")) {
            zipFileName = ftpFileName.replace(".zip", "");
        } else {
            ftpFileName += ".zip";
        }
        String tmpZipFilePath = tmpFilePath + File.separator + ftpFileName;
        String tmpZipFileDir = tmpFilePath + File.separator + zipFileName;
        log.info("##########上传压缩包，开始");
        long startTime = System.currentTimeMillis();    //获取开始时间
        try {
            serverResponse = planningReviewService.uploadZipFile(ywid, ywxl, userId, userName, tmpZipFileDir, version);
        } catch (Exception e) {
            log.error("##########附件上传失败：", e);
            return ServerResponse.createByErrorCodeMessage(1003,"附件上传失败！");
        }
        long endTime = System.currentTimeMillis();    //获取结束时间
        log.info("##########上传压缩包，用时：{}ms", endTime - startTime);
        /** 删除临时文件 */
        FileUtil.delFile(tmpZipFilePath);
        FileUtil.delFile(tmpZipFileDir);
        return serverResponse;
    }
}
